import { Color } from 'https://unpkg.com/three/build/three.module.js';
import { initShaders } from '../jsm/Utils.js';
import lib from '../jsm/ThreeLib.js';

window.onload = function () {

    const backColor = new Color("rgba(0,0,0,1)");

    const canvas = document.getElementById("canvas");
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;

    const gl = canvas.getContext("webgl");
    //开启颜色合成,才会有透明度的感觉
    gl.enable(gl.BLEND);
    gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);

    //初始化着色器
    initShaders(gl,
        document.querySelector("#vertexShader").innerText,
        document.querySelector("#fragmentShader").innerText);

    lib.clearCanvas(gl, backColor, 0);

    const a_Position = gl.getAttribLocation(gl.program, "a_Position");
    const a_PointSize = gl.getAttribLocation(gl.program, "a_PointSize");
    const u_FragColor = gl.getUniformLocation(gl.program, "u_FragColor");


    const arr = [];


    canvas.addEventListener("click", function (event) {
        const { clientX, clientY } = event;
        const { left, top, width, height } = canvas.getBoundingClientRect();
        const [cssX, cssY] = [clientX - left, clientY - top];

        var [x, y] = [lib.GetPosiOfX(width, cssX), lib.GetPosiOfY(height, cssY)];

        arr.push({
            x: x,
            y: y,
            size: Math.floor((Math.random() * (30)) + 20),
            color: [0, 0, 1, Math.random()]
        });
        render();
    })



    function render() {
        lib.clearCanvas(gl, backColor, 0);
        arr.forEach(({ x, y, size, color }) => {
            gl.vertexAttrib3f(a_Position, x, y, 0.0);
            gl.vertexAttrib1f(a_PointSize, size);
            gl.uniform4fv(u_FragColor, color);
            //每次调用该函数都会清除绘制缓冲区,所以需要重头开始绘制一次
            gl.drawArrays(gl.POINTS, 0, 1);
        });
    }

}